﻿using System.Security.Claims;

namespace PmSoft.Web.Abstractions.Authorization;

public static class ClaimsPrincipalExtensions
{
	/// <summary>
	/// 获取当前用户的用户 ID。
	/// </summary>
	/// <param name="principal">用户声明对象。</param>
	/// <returns>用户 ID。</returns>
	public static int? GetUserId(this ClaimsPrincipal principal)
	{
		if (principal == null)
		{
			throw new ArgumentNullException(nameof(principal));
		}
		var claim = principal.FindFirst(ClaimTypes.NameIdentifier);
		if (claim == null || !int.TryParse(claim.Value, out var userId))
		{
			return default;
		}
		return userId;
	}
	/// <summary>
	/// 获取当前用户的租户类型。
	/// </summary>
	/// <param name="principal">用户声明对象。</param>
	/// <returns>租户类型。</returns>
	public static string? GetTenantType(this ClaimsPrincipal principal)
	{
		if (principal == null)
		{
			throw new ArgumentNullException(nameof(principal));
		}
		var claim = principal.FindFirst("TenantType");
 
		return claim?.Value;
	}
	/// <summary>
	/// 获取当前用户户的用户类型。
	/// </summary>
	/// <param name="principal">用户声明对象。</param>
	/// <returns>用户类型。</returns>
	public static string? GetUserType(this ClaimsPrincipal principal)
	{
		if (principal == null)
		{
			throw new ArgumentNullException(nameof(principal));
		}
		var claim = principal.FindFirst("UserType");
		return claim?.Value;
	}
}
